//
//  JCReportHomeCell.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/30.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCReportHomeCell.h"
#import "JCReportModel.h"
#import "NSDate+CM_DateTools.h"
@import Charts;

@interface JCReportHomeCell ()

@property (weak, nonatomic) IBOutlet UIView *toolBackView;
@property (weak, nonatomic) IBOutlet LineChartView *upLineView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *dateBtns;
@property (weak, nonatomic) JCReportListModel *maxModel;
@property (weak, nonatomic) IBOutlet UILabel *durationValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingsValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *caroriesValueLabel;

@end

@implementation JCReportHomeCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [self configChartView:_upLineView];
    _toolBackView.layer.cornerRadius = 10;
    _toolBackView.layer.masksToBounds = YES;
    _toolBackView.frame = CGRectMake(0, 5, kYFScreenWidth / 7.0, 20);
    for (UIButton *btn in _dateBtns) {
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    }
}

- (void)setDailyModels:(NSArray<JCReportListModel *> *)dailyModels{
    _dailyModels = dailyModels;
    [self loadData];
}

- (void)loadData{
    NSInteger swingCount = 0;
    NSInteger maxWeek = 0;
    NSInteger swingTotal = 0;
    NSInteger durationTotal = 0;
    NSInteger calTotal = 0;
    NSMutableArray *swings = [NSMutableArray array];
    NSMutableArray *duration = [NSMutableArray array];
    NSMutableArray *calories = [NSMutableArray array];
    
    for (JCReportListModel *model in _dailyModels) {
        [swings addObject:@(model.swings.integerValue)];
        [duration addObject:@(model.duration.integerValue)];
        [calories addObject:@(model.caroline.integerValue)];
        if (swingCount < model.swings.integerValue) {
            swingCount = model.swings.integerValue;
            maxWeek = model.week.integerValue;
        }
        swingTotal += model.swings.integerValue;
        durationTotal += model.duration.integerValue;
        calTotal += model.caroline.integerValue;
    }
    if (_toolBackView) {
        for (UIButton *btn in _dateBtns) {
            btn.selected = NO;
        }
        _maxModel = _dailyModels[maxWeek];
        ((UIButton *)_dateBtns[maxWeek]).selected = YES;
        _toolBackView.center = ((UIButton *)_dateBtns[maxWeek]).center;
    }
    
    LineChartDataSet *powerData = [self loadDataWithSouceData:swings
                                                    fromColor:[UIColor clearColor]
                                                      toColor:UIColorFromHex(0x2bcae8)
                                                        label:@"挥拍"
                                                     lineView:_upLineView];
    LineChartDataSet *speedData = [self loadDataWithSouceData:duration
                                                    fromColor:[UIColor clearColor]
                                                      toColor:UIColorFromHex(0x29d9c2)
                                                        label:@"时间"
                                                     lineView:nil];
    LineChartDataSet *calorieaData = [self loadDataWithSouceData:calories
                                                       fromColor:[UIColor clearColor]
                                                         toColor:UIColorFromHex(0xe6417b)
                                                           label:@"卡洛里"
                                                        lineView:nil];
    _upLineView.data = [[LineChartData alloc] initWithDataSets:@[powerData,speedData,calorieaData]];
    
    if (_toolBackView) {
        _swingsValueLabel.text = _maxModel.swings;
        _durationValueLabel.text = [NSDate convertToHourMinFormateWithMin:_maxModel.duration.integerValue];
        _caroriesValueLabel.text = _maxModel.caroline;
    }else{
        _swingsValueLabel.text = @(swingTotal).stringValue;
        _durationValueLabel.text = [NSDate convertToHourMinFormateWithMin:durationTotal];
        _caroriesValueLabel.text = @(calTotal).stringValue;
    }
}

- (IBAction)dateAction:(UIButton *)sender {
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        _toolBackView.center = sender.center;
    } completion:^(BOOL finished) {
        
    }];
    for (UIButton *btn in _dateBtns) {
        btn.selected = NO;
    }
    sender.selected = YES;
    if (_delegate && [_delegate respondsToSelector:@selector(changeWeekDay:)]) {
        [_delegate changeWeekDay:sender.tag];
    }
    
    _swingsValueLabel.text = _dailyModels[sender.tag].swings;
    _durationValueLabel.text = [NSDate convertToHourMinFormateWithMin:_dailyModels[sender.tag].duration.integerValue];
    _caroriesValueLabel.text = _dailyModels[sender.tag].caroline;
}

- (void)configChartView:(LineChartView *)chartView{
    chartView.descriptionText = @"";//隐藏描述文字
    chartView.noDataText = @"";// 设置没有数据的显示内容
    chartView.legend.enabled = NO;
    chartView.scaleYEnabled = NO;//取消Y轴缩放
    chartView.scaleXEnabled = NO;//取消X轴缩放
    chartView.scaleEnabled = NO;// 缩放
    chartView.doubleTapToZoomEnabled = NO;//取消双击缩放
    chartView.dragDecelerationEnabled = NO;//拖拽后是否有惯性效果
    chartView.dragDecelerationFrictionCoef = 0;//拖拽后惯性效果的摩擦系数(0~1)，数值越小，惯性越不明显
        chartView.rightAxis.enabled = NO;//不绘制右边轴的信息
        chartView.leftAxis.enabled = NO;//不绘制左边轴的信息
    chartView.xAxis.axisLineColor = [UIColor clearColor];
    chartView.xAxis.enabled = NO;
    
    ChartYAxis *leftAxis = chartView.leftAxis;
    leftAxis.enabled = NO;
    ChartYAxis *rightAxis = chartView.rightAxis;
    rightAxis.labelTextColor = UIColorFromHex(0xffffff);
    //    rightAxis.axisMaximum = 300.0;
//    rightAxis.axisMinimum = 6;
    rightAxis.drawZeroLineEnabled = YES;
    rightAxis.enabled = YES;
    rightAxis.drawGridLinesEnabled = NO;
    rightAxis.drawLabelsEnabled = NO;
    rightAxis.drawAxisLineEnabled = NO;
    rightAxis.zeroLineWidth = 1;
    rightAxis.zeroLineColor = UIColorFromHex(0x999999);
}

- (LineChartDataSet *)loadDataWithSouceData:(NSArray *)lineSourceData
                                  fromColor:(UIColor *)fromColor
                                    toColor:(UIColor *)toColor
                                      label:(NSString *)label
                                   lineView:(LineChartView *)lineView{
    
    NSMutableArray *arr = [NSMutableArray array];
    CGFloat maxValue = 0;
    for (NSInteger i = 0; i < lineSourceData.count; i++) {
        NSNumber *number = lineSourceData[i];
        CGFloat value = [number floatValue];
        if ([label isEqualToString:@"力量"]) {
            value = value / 10.0;
        }
        maxValue = maxValue > value ? maxValue : value;
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:value];
        [arr addObject:entry];
    }
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:arr label:label];
    set.lineWidth = 2;
    set.drawValuesEnabled = NO;
    set.highlightEnabled = YES;
    set.highlightColor = [UIColor clearColor];
    set.drawCirclesEnabled = NO;
    set.cubicIntensity = 0.2;
    set.circleRadius = 5.0f;
    set.drawCircleHoleEnabled = NO;
    
    //    set.circleHoleRadius = 4.0f;//空心的半径
    //    set.circleHoleColor = [UIColor clearColor];//空心的颜色
    //    set.circleColors = @[[UIColor colorWithRed:0.114 green:0.812 blue:1.000 alpha:1.000]];
    set.mode = LineChartModeLinear;
    set.drawFilledEnabled = YES;
    if ([label isEqualToString:@"力量"]) {
        set.axisDependency = AxisDependencyLeft;
    }else{
        set.axisDependency = AxisDependencyRight;
    }
    
    [set setColor:toColor];
    NSArray *gradientColors = @[(id)fromColor.CGColor,
                                (id)toColor.CGColor];
    CGGradientRef gradientRef = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
    set.fillAlpha = 0.8f;
    set.fill = [ChartFill fillWithLinearGradient:gradientRef angle:90.0f];
    CGGradientRelease(gradientRef);
    if (lineView) {
        [lineView animateWithYAxisDuration:1.0f easingOption:ChartEasingOptionEaseInOutQuad];
    }
    return set;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end
